<?php
if (!defined('BASEPATH'))
	exit('No direct script access allowed');

class landcrop_manage extends CI_Controller {
	var $data = array();
	var $ServerPath = "/ci_ube";
	public function __construct() {
		parent::__construct();
		$this -> output -> cache(0);
		$this -> load -> library('PolylineEncoder');

		$this -> load -> model('Polygon');
		$this -> data['nowmenu'] = "land";
		$this -> data['title'] = "Static Content Management";
		$this -> data['current_module'] = site_url("landcrop_manage");
		$this -> data['role_id'] = $this -> session -> userdata('role_id');
	}

	public function index() {

		$query = $this -> db -> query("SELECT * FROM  `landtype`");
		$documentTypr = array();
		$documentTypr[] = "Select";
		foreach ($query->result() as $row) {
			$documentTypr[$row -> landtypeid] = $row -> name;
		}

		$this -> data['landtype'] = $documentTypr;
		$this -> load -> view('landcrop/landcrop_dashboard', $this -> data);
	}

	public function getlandall() {
		$reul = "";

		$query = $this -> db -> query("SELECT
    `land`.`landid`
    , `land`.`name` AS `land_name`
    , `land_polygon`.`Size`
   , `landtype`.`hexcolor`,`landtype`.landtypeid, `landtype`.`name` as landType
			    , `land`.`Lat`, `land`.`Lng`
FROM
    `ube`.`land`
    INNER JOIN `ube`.`land_polygon` 
        ON (`land`.`land_polygonid` = `land_polygon`.`land_polygonid`)
    LEFT JOIN `ube`.`landtype` 
        ON (`land`.`landtypeid` = `landtype`.`landtypeid`)");
		$resultArray = array();
		$landID;
		foreach ($query->result() as $row) {

			$resultJson = array();
			$landID = $row -> landid;
			$resultJson['id'][] = $row -> landid;
			$resultJson['landid'][] = sprintf("%06d", $row -> landid);
			$resultJson['landcolor'][] = "#" . $row -> hexcolor;
			$resultJson['landname'][] = $row -> land_name;
			$resultJson['landtype'][] = $row -> landType;
			$resultJson['Lat'][] = $row -> Lat;
			$resultJson['Lng'][] = $row -> Lng;
			$queryPolygon = $this -> db -> query("SELECT * FROM land_polygon_map where LAND_ID=" . $row -> landid);

			$arrayTmp = array();
			foreach ($queryPolygon->result() as $rowPolygon) {
				$arrayTmp[] = $rowPolygon -> Lat . "," . $rowPolygon -> Log;
			}

			$resultJson['landsize'][] = $row -> Size;
			$resultJson['polygon'][] = $arrayTmp;

			$queryCrop = $this -> db -> query("SELECT landcropid FROM landcrop where landid=" . $row -> landid);
			foreach ($queryCrop->result() as $row) {
				$queryCropPoly = $this -> db -> query("SELECT * FROM landcrop_polygon_map where LAND_ID=" . $row -> landcropid);
				$resultJson['lancropid'][] =$row -> landcropid;
				$arrayTmp = array();
				foreach ($queryCropPoly->result() as $rowCrop) {
					$arrayTmp[] = $rowCrop -> Lat . "," . $rowCrop -> Log;

				}
				$resultJson['lancrop'][] = $arrayTmp;
			}

		
			$resultArray[] = $resultJson;
		}

		echo json_encode($resultArray);
	}

	public function getlandcropmap($landid) {
		$staticMapUrl = "http://maps.google.com/maps/api/staticmap?size=250x250";
		$points2 = array();
		$numPoints = 0;
		$query2 = $this -> db -> query("SELECT * FROM  `land_polygon_map` where LAND_ID=" . $landid);

		foreach ($query2->result() as $row) {
			$points2[$numPoints][0] = $row -> Lat;
			$points2[$numPoints][1] = $row -> Log;
			$numPoints++;
		}
		$parsedCoords = $this -> Polygon -> parseCoordData($points2);
		$staticMapUrl .= "&path=fillcolor:0xFF00FF33|enc:" . $parsedCoords[0];
		$query = $this -> db -> query("SELECT landcropid FROM  `landcrop`  where landid=" . $landid);
		$points2 = array();
		$numPoints = 0;
		foreach ($query->result() as $row) {
			$query2 = $this -> db -> query("SELECT * FROM  `landcrop_polygon_map` where LAND_ID=" . $row -> landcropid);

			foreach ($query2->result() as $row) {
				$points2[$numPoints][0] = $row -> Lat;
				$points2[$numPoints][1] = $row -> Log;
				$numPoints++;
			}
		}
		if (count($points2)) {
			$parsedCoords = $this -> Polygon -> parseCoordData($points2);

			$staticMapUrl .= "&path=fillcolor:0x0000FF33|enc:" . $parsedCoords[0];
		}
		$staticMapUrl .= "&sensor=false";
		echo $staticMapUrl;

	}

	public function popup_uploadland() {
		$query = $this -> db -> query("SELECT * FROM  `land_document_type`");
		$documentTypr = array();
		$documentTypr[] = "Select";
		foreach ($query->result() as $row) {
			$documentTypr[$row -> land_document_type_id] = $row -> land_document_type_name;
		}
		$this -> data['documenttype'] = $documentTypr;

		$query = $this -> db -> query("SELECT * FROM  `landtype`");
		$documentTypr = array();
		$documentTypr[] = "Select";
		foreach ($query->result() as $row) {
			$documentTypr[$row -> landtypeid] = $row -> name;
		}
		$this -> data['landtype'] = $documentTypr;
		$this -> load -> view('landcrop/landcrop_upload', $this -> data);

	}

	public function getvendorlst() {
		$query = $this -> db -> query('SELECT uuid,vfirstname,vlastname FROM vendor where vfirstname like ' . "'%" . $_REQUEST['queryString'] . "%'");
		foreach ($query->result() as $row) {
			echo "<li onClick=\"fill(" . $row -> uuid . ",'" . $row -> vfirstname . "  " . $row -> vlastname . "');\">" . $row -> vfirstname . "  " . $row -> vlastname . '</li>';
		}
	}

	public function getland_data() {

	}

	public function getcropdetail() {

		$htmlResult = '<table class="listing form" cellpadding="0" cellspacing="0">
           <tr>
               <th class="full" colspan="3">ข้อมูลที่ดินเพาะปลูกเดิม</th>
           </tr>
           <tr>
                <td width="189" height="96">';

		// <strong>A ชื่อเกษตรกร</strong></td>
		// <td width="348">ประเภทที่ดิน: UBE<br>
		// ขนาดที่ดิน: 19 ไร่<br>
		// ผลผลิตต่อไร่: 1,000 ตัน<br>
		// Phase: 1 เริ่มปักกิ่ง<br>
		// คุณภาพ: ***</td>
		// <td width="191" rowspan="2"><p>แสดงเป็น static</p>
		// <p>เมื่อคลิกแสดงผลเป็นแบบ google API<br>
		// ที่สามารถแสดง map + info ด้านซ้าย</p></td>
		// </tr>
		// <tr>
		//
		// </tr>
		// </table>
	}

	// public function getvendorlst($param) {
	// //$_REQUEST['queryString']=$param;
	// $query = $this -> db -> query('SELECT uuid,vfirstname,vlastname FROM vendor where vfirstname like ' . "'%" . urldecode($param) . "%'");
	// $resultsdd = array();
	//
	// foreach ($query->result() as $row) {
	// $resultsdd[] = $row -> vfirstname . "  " . $row -> vlastname;
	//
	// }
	// echo json_encode($resultsdd);
	// }

	public function uploadgpx($landid) {

		if (isset($_FILES["uploadfile"]["name"]) && $_FILES["uploadfile"]["name"] != "") {
			$save_tmp = time() . $_FILES["uploadfile"]["name"];
			if (substr($_FILES["uploadfile"]["name"], -4) == ".kml") {

				$saveKMLPath = $_SERVER['DOCUMENT_ROOT'] . "/ci_ube/data/kml/" . $save_tmp;
				if (move_uploaded_file($_FILES["uploadfile"]["tmp_name"], $saveKMLPath)) {

					$xml = simplexml_load_file($saveKMLPath);
					$count = 0;
					$LandID = $landid;
					foreach ($xml->Document->Placemark as $place) {

						// $checkHaveInDB = $this -> db -> query("SELECT landcropid FROM landcrop where landcropname='" . $place -> name . "'");
						$lastInsertID = "";

						$AddressID = "";
						$count = $count + 1;
						$LandName_tm = "";
						$datatmp = array();
						// if ($checkHaveInDB -> num_rows() > 0) {
						// $row = $checkHaveInDB -> row();
						// $LandID = $row -> landcropid;
						// $this -> db -> query("delete from  landcrop_polygon_map where LAND_ID=" . $LandID);
						// } else {
						$datatmp = array('landcropname' => "" . $place -> name);
						$LandName_tm = $place -> name;
						foreach ($place->LookAt as $lookAtArea) {
							$datatmp['Lat'] = $lookAtArea -> latitude;
							$datatmp['Lng'] = $lookAtArea -> longitude;

						}

						// }
						$datatmp['landid'] = $LandID;
						$this -> db -> insert('landcrop', $datatmp);
						$LandID = $this -> db -> insert_id();
						$tmpPoligon = "";
						$latTmp = "";
						$logtmp = "";
						foreach ($place->Polygon as $areaPolygon) {
							$tmp1 = trim($areaPolygon -> outerBoundaryIs[0] -> LinearRing -> coordinates);
							$tmp1 = str_replace(",0", "#", $tmp1);
							$tmp1 = str_replace(",", " ", $tmp1);
							$tmp1 = str_replace("#", ",", $tmp1);
							$tmp1 = substr($tmp1, 0, strlen($tmp1) - 1);
							$tmp1 = explode(",", $tmp1);
							$tmpPolygon = "";
							for ($i = 0; $i < count($tmp1); $i++) {
								$tmpArray = array();
								$tmpArray = explode(" ", trim($tmp1[$i]));
								for ($j = 0; $j < count($tmpArray); $j = $j + 2) {
									$LatLongTmp = array();
									$LatLongTmp['Log'] = $tmpArray[$j];
									$LatLongTmp['Lat'] = $tmpArray[$j + 1];
									$LatLongTmp['LAND_ID'] = $LandID;
									$this -> db -> insert('landcrop_polygon_map', $LatLongTmp);

									$tmpPolygon = $tmpPolygon . $tmpArray[$j + 1] . " " . $tmpArray[$j] . ",";
								}
								$logtmp = $tmpArray[0];
								$latTmp = $tmpArray[1];
							}
							$tmpPolygon = substr($tmpPolygon, 0, strlen($tmpPolygon) - 1);
							$sqlInsertPoligon = "INSERT INTO landcrop_polygon(`name`,`polygon`) VALUES ('" . $LandName_tm . "', GeomFromText('POLYGON(( " . $tmpPolygon . "))'))";
							$this -> db -> query($sqlInsertPoligon);
							$polygonID = $this -> db -> insert_id();
							$calculateArea = $this -> db -> query("SELECT area(polygon) as areasize FROM  landcrop_polygon where land_polygonid=" . $polygonID);
							$rowResultArea = $calculateArea -> row();

							$areaSize = (($rowResultArea -> areasize / 1000000) / 0.0016);
							$this -> db -> query("update landcrop set landcrop_polygonid=" . $polygonID . ",Lat=" . $latTmp . ",Lng=" . $logtmp . " where landcropid=" . $LandID);

							$this -> db -> query("update landcrop_polygon set Size=" . $areaSize . " where land_polygonid=" . $polygonID);
						}

					}
					echo $LandID;
				}
			} else {
				$saveKMLPath = $_SERVER['DOCUMENT_ROOT'] . "/ci_ube/data/gpx/" . $save_tmp;
				if (move_uploaded_file($_FILES["uploadfile"]["tmp_name"], $saveKMLPath)) {

					$xml = simplexml_load_file($saveKMLPath);
					$count = 0;
					$LandID = "";
					foreach ($xml -> trk as $place) {

						$checkHaveInDB = $this -> db -> query("SELECT landcropid FROM land where landcropname='" . $place -> name . "'");
						$lastInsertID = "";

						$AddressID = "";
						$count = $count + 1;
						$LandName_tm = "";
						$dataLand = array();
						// if ($checkHaveInDB -> num_rows() > 0) {
						// $row = $checkHaveInDB -> row();
						// $LandID = $row -> landcropid;
						// $this -> db -> delete('land_polygon_map', array('LAND_ID' => $LandID));
						// } else {

						$dataLand['landcropname'] = "" . $place -> name;
						$LandName_tm = $place -> name;
						if (count($place -> trkseg -> trkpt) > 0) {
							$attrs = $place -> trkseg[0] -> trkpt -> attributes();
							$dataLand['Lat'] = $attrs['lat'];
							$dataLand['Lng'] = $attrs['lon'];
						}
						// }

						// $dataLandAddress = array('land_docid' => $landDocID);
						// $this -> db -> insert('land_address', array('housenum' => ""));

						// $dataLand['land_addressid'] = $this -> db -> insert_id();
						//$dataLand['Updatetime']= date("d-m-o")." ".date('H:i:s');
						$this -> db -> insert('landcrop', $dataLand);
						$LandID = $this -> db -> insert_id();

						$tmpPolygonX = "";
						$latTmp = "";
						$logtmp = "";
						foreach ($place -> trkseg->trkpt as $locationRow) {
							$attrs = $locationRow -> attributes();
							$LatLongTmp = array();
							$LatLongTmp['Lat'] = $attrs['lat'];
							$LatLongTmp['Log'] = $attrs['lon'];
							$latTmp = $attrs['lat'];
							$logtmp = $attrs['lon'];
							$LatLongTmp['LAND_ID'] = $LandID;
							$this -> db -> insert('landcrop_polygon_map', $LatLongTmp);

						}

						$this -> db -> query("update landcrop set Lat=" . $latTmp . ",Lng=" . $logtmp . " where landcropid=" . $LandID);

					}
					echo $LandID;
				}
			}
		}
	}

	public function getvendorcrop($verdor_id) {
		$query = $this -> db -> query("SELECT
    `vendor`.`vfirstname`
    , `vendor`.`vlastname`
    , `landcrop`.`landcropname`
    , `vendor`.`vfirstname`
    , `vendor`.`vlastname`,`landcrop`.`verdor_id`
FROM
    `ube`.`landcrop` 
    INNER JOIN `ube`.`vendor` 
        ON (`vendor`.`uuid` = `landcrop`.`verdor_id`) where landid=" . $verdor_id);
		echo "<ul>";
		foreach ($query->result() as $row) {
			echo "<li><a href='javascript:findcrop(" . $row -> verdor_id . ");'>" . $row -> vfirstname . "</a></li>";
		}
		echo "</ul>";

	}

	public function updatelandcropinfo() {

		$record = array();
		$record['landid'] = $_REQUEST['landid'];
		$record['uuid'] = $_REQUEST['uuid'];
		$this -> db -> query("update landcrop set landid=" . $_REQUEST['landid'] . ",verdor_id=" . $_REQUEST['uuid'] . " where landcropid=" . $_REQUEST['landcropid']);
		echo "Update Complete";

	}

}
?>